using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BruteMerge.ExecutableLauncher.Interfaces;

namespace BruteMerge.ExecutableLauncher
{
    internal class ResourceProvider
    {
        private readonly Dictionary<string, string> _resolvationCache;
        private readonly Assembly _assembly;

        public bool CanBeLoaded(string name)
        {
            return _resolvationCache.ContainsKey(name);
        }

        public IEnumerable<string> Resources
        {
            get { return _resolvationCache.Keys; }
        }

        public ResourceProvider(Assembly assembly, IEnumerable<IResourceAlias> aliases)
        {
            _assembly = assembly;
            _resolvationCache = aliases.ToDictionary(k => k.AliasName, v => v.ResourceName);
        }

        private Stream GetResourceStreamInternal(string name)
        {
            return _assembly.GetManifestResourceStream(name);
        }

        public Stream GetResourceStream(string name)
        {
            if (!CanBeLoaded(name))
                throw new Exception("Assembly " + name + " not found!");

            return GetResourceStreamInternal(_resolvationCache[name]);
        }

        public byte[] LoadBytes(string name)
        {
            using (var stream = GetResourceStream(name))
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int) stream.Length);

                return bytes;
            }
        }
    }
}